#include "StdAfx.h"
#include "AnsiCommand.h"

CAnsiCommand::CAnsiCommand()
{
}

CAnsiCommand::CAnsiCommand(CAnsiCommand::Action action, int parameterBuffer[], int parameterCount)
{
	this->action = action;

	// Based on action, determine parameter count and default parameters
	InitializeParameterCountAndDefaultParameters();

	// SGR can have as many parameters as possible
	if (this->action == SelectGraphicRendition)
		this->parameterCount = parameterCount;

	// Copy parameters, filling defaults if necessary
	if (this->parameterCount < parameterCount)
		ASSERT(FALSE); // Too many parameters

	VERIFY(this->parameterCount < maxParameterCount);

	for (int i = 0; i < this->parameterCount; i++)
    {
		if (i >= parameterCount || parameterBuffer[i] < 0)
            if (i >= this->defaultParameterCount)
                ASSERT(FALSE); // Parameter cannot be ommitted
			else
				this->parameterBuffer[i] = this->defaultParameterBuffer[i];
        else
			this->parameterBuffer[i] = parameterBuffer[i];
    }

	if (this->action == EraseInDisplay)
		ASSERT(this->parameterBuffer[0] >= 0 && this->parameterBuffer[0] <= 2);

	if (this->action == DeviceStatusReport)
		ASSERT(this->parameterBuffer[0] == 0);
}

void CAnsiCommand::InitializeParameterCountAndDefaultParameters()
{
	static int default0[1] = {0};
	static int default1[1] = {1};
	static int default2[2] = {1, 1};

	switch (this->action)
	{
	case CursorUp:
	case CursorDown:
	case CursorForward:
	case CursorBack:
	case CursorNextLine:
	case CursorPrevLine:
		this->parameterCount = 1;
		this->defaultParameterCount = 1;
		this->defaultParameterBuffer = default1;
		break;

	case CursorHorizontal:
		this->parameterCount = 1;
		this->defaultParameterCount = 0;
		this->defaultParameterBuffer = NULL;
		break;

	case CursorPosition:
		this->parameterCount = 2;
		this->defaultParameterCount = 2;
		this->defaultParameterBuffer = default2;
		break;

	case EraseInDisplay:
	case EraseInLine:
		this->parameterCount = 1;
		this->defaultParameterCount = 1;
		this->defaultParameterBuffer = default0;
		break;

	case SelectGraphicRendition:
		this->parameterCount = 0;
		this->defaultParameterCount = 0;
		this->defaultParameterBuffer = NULL;
		break;

	case InsertLine:
		this->parameterCount = 1;
		this->defaultParameterCount = 1;
		this->defaultParameterBuffer = default1;
		break;

	case DeviceStatusReport:
		this->parameterCount = 1;
		this->defaultParameterCount = 0;
		this->defaultParameterBuffer = NULL;
		break;

	case SaveCursorPosition:
	case RestoreCursorPosition:
		this->parameterCount = 0;
		this->defaultParameterCount = 0;
		this->defaultParameterBuffer = NULL;
		break;
	}
}